/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-10-17 14:15:19
 * Last Modified: 2017-09-08 18:44:34
 * File Name: rpc/client/sms.go
 * Description:
 */

//
package sms

import (
	"crypto/tls"
	"fmt"

	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

var (
	smsAddr   string
	smsHost   string
	smsAppkey string
	smsSecret string
)

/*
	发送模板短信
*/
func SendSMSTpl(mobile string, tplId int, args map[string]string) bool {
	if mobile == "" {
		return false
	}
	//usb := utility.NewURLSignBuilder("a7ce91dc3fd343ee9ea8ac9fc9266ad4", "d08840e75d1d46de9eea2d411233c2b5", "https://qk.skyids.com/sms/send-by-tpl")
	usb := utility.NewURLSignBuilder(smsAppkey, smsSecret, fmt.Sprintf("http://%s/sms/send-by-tpl", smsAddr))
	//	reqURL := "https://qk.skyids.com/sms/send-by-tpl?appkey=a7ce91dc3fd343ee9ea8ac9fc9266ad4"
	reqURL := usb.BuildURL()
	b := httplib.Post(reqURL)
	b.SetHost(smsHost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	body := make(map[string]interface{})
	body["mobile"] = []string{mobile}
	body["tpl_id"] = tplId
	body["args"] = args
	log.Debugf("url:%s ", reqURL)
	log.Debugf("body:%v ", body)

	b.JSONBody(body)
	var resp struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
	}
	if err := b.ToJSON(&resp); err != nil {
		log.Warnf("SendSMSTpl error: %s, mobile: %s, tplId: %d, args: %#v", err.Error(), mobile, tplId, args)
		return false
	}
	dt, err := b.Bytes()
	log.Debugf("SendSMSTpl: %s, %v", dt, err)
	return resp.Code == 0
}

func init() {
	smsAddr = beego.AppConfig.DefaultString("sms::sms_addr", "testqk.skyids.com")
	smsHost = beego.AppConfig.DefaultString("sms::sms_host", "testqk.skyids.com")
	smsAppkey = beego.AppConfig.DefaultString("sms::sms_appkey", "a7ce91dc3fd343ee9ea8ac9fc9266ad4")
	smsSecret = beego.AppConfig.DefaultString("sms::sms_secret", "d08840e75d1d46de9eea2d411233c2b5")
}
